package com.avcdata.aoscustommade.utils.http;

import android.content.Context;
import android.content.Intent;

import com.avcdata.aoscustommade.activity.CitySelect_Activity;
import com.avcdata.aoscustommade.activity.Login_Activity;
import com.avcdata.aoscustommade.bean.BaseResponseBean;
import com.avcdata.aoscustommade.utils.AvcLogUtils;
import com.avcdata.aoscustommade.utils.AvcNetworkUtil;
import com.avcdata.aoscustommade.utils.TextUitl;
import com.avcdata.aoscustommade.utils.ToastUtils;
import com.avcdata.aoscustommade.utils.json.AvcJsonUtils;

import org.apache.http.Header;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Map;


/**
 * 请求Handler类
 *
 * Created by zyh on 2017/5/19.
 */

public class AvcJsonHttpResponseHandler extends AvcResponseHandler {

    private Context context;

    private Class classObject;

    /**
     * 构造方法
     * @param context 上下文对象
     */
    public AvcJsonHttpResponseHandler(Context context) {
        this.context = context;
    }

    /**
     * 构造方法
     *
     * @param context 上下文对象
     * @param classObject bean对象
     */
    public AvcJsonHttpResponseHandler(Context context, Class classObject) {
        this.context = context;
        this.classObject = classObject;
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        super.onFailure(statusCode, headers, responseString, throwable);
        handleError(throwable);
    }


    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
        super.onFailure(statusCode, headers, throwable, errorResponse);
        handleError(throwable);
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
        super.onFailure(statusCode, headers, throwable, errorResponse);
        handleError(throwable);
    }

    /**
     * 处理异常
     * @param throwable
     */
    private void handleError(Throwable throwable) {

        AvcLogUtils.d("网络请求error:"+throwable.getMessage());

        String msg = "无法连接服务器";

        if (throwable instanceof SocketTimeoutException){
            ToastUtils.showShort(context, "请连接网络");
        } else if (throwable instanceof ConnectTimeoutException){
            ToastUtils.showShort(context, "连接超时");
        } else if (throwable instanceof HttpHostConnectException) {
            if (AvcNetworkUtil.isNetworkAvailable(context)){
                ToastUtils.showShort(context, msg);
            } else {
                ToastUtils.showShort(context, "网络连接不可以");
            }
        }else if (throwable instanceof IOException
                && null != throwable.getMessage()
                && throwable.getMessage().contains("UnknownHostException")) {
            if (AvcNetworkUtil.isNetworkAvailable(context)) {
                ToastUtils.showShort(context, msg);
            } else {
                ToastUtils.showShort(context, "网络连接不可用");
            }
        } else if (!TextUitl.isEmpty(throwable.getMessage())) {
            if ("Bad Gateway".equalsIgnoreCase(throwable.getMessage().trim())
                    || "not found".equalsIgnoreCase(throwable.getMessage().trim())) {
                if (AvcNetworkUtil.isNetworkAvailable(context)) {
                    ToastUtils.showShort(context, msg);
                } else {
                    ToastUtils.showShort(context, "网络连接不可用");
                }
            } else if ("null".equalsIgnoreCase(throwable.getMessage().trim())) {
                ToastUtils.showShort(context, "服务器异常");
            } else {
                if (throwable.getMessage().length() > 15) {
                    ToastUtils.showShort(context,
                            throwable.getMessage().substring(0, 15) + "...");
                } else {
                    ToastUtils.showShort(context, throwable.getMessage());
                }
            }
        }

        //异常回调
        onFailure();
        onFailure(new BaseResponseBean());
        onFailure(throwable);
    }

    /**
     * 调用的地方可以重写
     */
    public void onFailure(){

    }

    /**
     * 传递错误map
     * @param baseResponseBean
     */
    public void onFailure(BaseResponseBean baseResponseBean){

    }


    /**
     * 调用的地方可以重写
     * @param throwable 异常
     */
    public void onFailure(Throwable throwable){

    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject jsonobject) {
        try {
            super.onSuccess(statusCode, headers, jsonobject);
            //返回bean对象
            if (null != classObject){
                Object object = AvcJsonUtils.jsonObjectToObject(jsonobject, classObject);
                BaseResponseBean bean = (BaseResponseBean) object;
                if (!bean.isSuccess()){
                    if (null == bean.getMessage()){
                        ToastUtils.showShort(context, "服务器异常，请稍后再试");
                    } else {
                        if ("用户已过期，请重新登录".equals(bean.getMessage())){
                            Intent intent = new Intent(context, Login_Activity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            context.startActivity(intent);
                        }
//                        ToastUtils.showShort(context, bean.getMessage());
                    }
//                    onFailure();
                    onFailure(bean);
                }else {
                    onSuccess(object);
                }
            } else {
                //返回json对象
                Map<String, Object> map = AvcJsonUtils.jsonObjectToMap(jsonobject);
                BaseResponseBean baseResponseBean = (BaseResponseBean) AvcJsonUtils.jsonObjectToObject(jsonobject, BaseResponseBean.class);
                if ("false".equals(map.get("success")+"")) {
                    if (null == map.get("message") || "null".equals(map.get("message") + "")){
                        ToastUtils.showShort(context, "服务器异常，请稍后再试");
                    } else {
                        ToastUtils.showShort(context, map.get("message")+"");
                    }
                    onFailure();
                    onFailure(baseResponseBean);
                } else {
                    onSuccess(map);
                    onSuccess(jsonobject);
                }

            }
        } catch (Exception e) {
            onFailure();
            e.printStackTrace();
        }
    }

    /**
     * 成功后回调，子类可重写覆盖
     *
     * @param object
     */
    public void onSuccess(Object object) {
    }

    /**
     * 成功后回调，子类可重写覆盖
     *
     * @param map map对象
     */
    public void onSuccess(Map<String, Object> map) {

    }

    /**
     * 成功后回调，子类可重写覆盖
     *
     * @param jsonobject JSONObject对象
     */
    public void onSuccess(JSONObject jsonobject) {

    }
}
